// Schema、Model、Entity或者Documents的关系请牢记，Schema生成Model，Model创造Entity，Model和Entity都可对数据库操作造成影响，但Model比Entity更具操作性。
const mongoose = require('mongoose')
// 连接数据库 如果不自己创建 默认test数据库会自动生成
mongoose.connect('mongodb://localhost:27017/minichat', {useNewUrlParser: true})

// 为这次连接绑定事件
const db = mongoose.connection
db.once('error', () => console.log('Mongo connection error'))
db.once('open', () => console.log('Mongo connection successed'))
/* ************* 定义模式loginSchema ************* */
const loginSchema = mongoose.Schema({
  username: String,
  password: String,
  nickname: String
})
/* ************* 定义模式RegisterSchema ************* */
const RegisterSchema = mongoose.Schema({
  username: String,
  password: String,
  nickname: String,
  email: String
})

/* ************* 定义模式UsersSchema ************* */
// const UsersSchema = mongoose.Schema({
//   users: [
//     {
//       userInfo: {
//         username: String,
//         password: String,
//         nickname: String,
//         email: String
//       }
//     }
//   ]
// })
/* ************* 定义模式UsersSchema ************* */
const UsersSchema = mongoose.Schema({
      username: String,
      userInfo: {
        username: { type: String, default: '' },
        password: { type: String, default: '' },
        nickname: { type: String, default: '' },
        email: { type: String, default: '' },
        headicon: { type: String, default: '' }
      },
      groupInfo: [{
        // 群成员
        affiliations: [],
        // 群人数
        affiliations_count: { type: Number, default: 0 },
        // 同意申请
        allowinvites: { type: Boolean, default: true },
        // 创建时间
        created: { type: Date, default: new Date().getTime() },
        custom: { type: String, default: '' },
        // 群描述
        discription: { type: String, default: '' },
        id: { type: String, default: '' },
        maxusers: { type: Number, default: 200 },
        membersonly: { type: Number, default: false },
        name: { type: String, default: '' },
        owner: { type: String, default: '' },
        // 是否公开群，默认是的
        public: { type: Boolean, default: true },
        // 加群审批true:需要审批 false：不需要审批
        shieldgroup: { type: Boolean, default: false },
        groupicon: { type: String, default: '' }
      }],
      groupMessageList: [{
        list: [{
          type: { type: String, default: '' },
          read: { type: Boolean, default: false },
          self: { type: Boolean, default: false },
          msg: { type: String, default: '' },
          headicon: { type: String, default: '' },
          time: { type: Date, default: new Date().getTime() }
        }],
        // 群ID
        groupid: { type: String, default: '' },
        // 群名
        name: { type: String, default: '' },
        // 群头像
        groupicon: { type: String, default: '' }
      }],
      friends: [{
        subscription: String,
        jid: String,
        name: String,
        groups: Array,
        headicon: String
      }],
      messageList: [{
        list: [{
          msg: String,
          time: Number,
          read: Boolean,
          self: Boolean,
          type: { type: String, default: '' }
        }],
        name: String,
        _id: String
      }],
      addNewFriends: [{
        from: { type: String, default: '' },
        to: { type: String, default: '' },
        fromJid: { type: String, default: '' },
        toJid: { type: String, default: '' },
        type: { type: String, default: '' },
        chatroom: { type: Boolean, default: false },
        status: { type: String, default: '' },
        code: { type: String, default: '' },
        presence_type: { type: String, default: '' },
        original_type: { type: String, default: '' },
        read: { type: Boolean },
        agree: { type: Boolean }
      }]
})
// 删除friends数组中的某一项
UsersSchema.methods.deleteFriend = function(jid) {
  // this代表当前拿到的数据
  // 删除friendds
  this.friends = this.friends.filter(f => f.jid !== jid)
  // 删除messageList
  this.messageList = this.messageList.filter(f => f['_id'] !== jid)
  // 这里直接更新
  this.save()
}
// 好友列表添加好友friends
UsersSchema.methods.addFriend = function(friendObj) {
  // this代表当前拿到的数据
  // 设置friendds
  this.friends.push(friendObj)
  // 这里直接更新
  this.save()
}
// 用户登录就设置friends数组
UsersSchema.methods.setFriend = function(friends) {
  // 这里直接更新
  const self = this
  // console.log(friends)
  // 这样不覆盖朋友对象中的headicon
  friends.forEach(item => {
    let index = self.friends.findIndex(f => f.name === item.name)
    // console.log(index)
    if (index !== -1) {
      // console.log(self.friends[index].headicon, item.headicon)
      if (!self.friends[index].headicon && item.headicon) {
        self.friends[index].headicon = item.headicon
      }
    } else {
      self.friends.push(item)
    }
  })
  self.save()
}
// 删除messagesList中的一项
UsersSchema.methods.deleteMessageList = function(jid) {
  // this代表当前拿到的数据
  this.messageList = this.messageList.filter(f => f['_id'] !== jid)
  // 这里直接更新
  this.save()
}
/* 关于addNewFriends */
// 添加
UsersSchema.methods.setAddNewFriends = function(message) {
  // this代表当前拿到的数据
  let tempitem = this.addNewFriends.filter(f => f.from === message.from) || []
  // 去除重复的
  if (!tempitem.length) {
    this.addNewFriends.push(message)
  }
  this.save()
}
// 修改添加好友信息，已读，已经同意，或者不同意
UsersSchema.methods.resetAddNewFriends = function(obj) {
 let tempitem = this.addNewFriends.find(f => f.fromJid === obj.jid) || {}
 tempitem.read = obj.read
 tempitem.agree = obj.agree
  this.save()
}
// addNewFriends删除其中符合条件的一项
UsersSchema.methods.deleteAddNewFriends = function(jid) {
  // this代表当前拿到的数据
  this.addNewFriends = this.addNewFriends.filter(f => f.fromJid !== jid)
  // 这里直接更新
  this.save()
}
// userInfo修改或者添加头像信息
UsersSchema.methods.resetHeadicon = function(str) {
  // console.log(str, '00000000000000')
  // this代表当前拿到的数据
  this.userInfo['headicon'] = str
  // 这里直接更新
  this.save()
}
// 群组信息的添加
UsersSchema.methods.setgroupOptions = function(option) {
  let index = this.groupInfo.findIndex(f => f.id === option.id)
  // 如果数据库里面找不到这个就直接推进去
  if (index === -1) {
    // console.log(index)
    this.groupInfo.push(option)
  } else {
    // 如果找到就替换
    this.groupInfo.splice(index, 1, option)
  }
  // 这里直接更新,更新找到的所有数据
  this.save()
}
// 群组头像的修改, 看要不要整个对象传进来直接切掉其他的就好****
UsersSchema.methods.resetgroupOption = function(option) {
  let result = this.groupInfo.filter(f => f.id === option.id)
  if (!result.length) {
    this.groupInfo.push(option)
  }
  // 这里直接更新
  this.save()
}
/* ************* 定义模式UsersSchema ************* */
const UsersInfoSchema = mongoose.Schema({
  username: String,
  password: String,
  nickname: String,
  email: String,
  headicon: String
})

/* ************* 定义模型Model ************* */
const Models = {
  // 所有已经登录的用户
  Login: mongoose.model('Login', loginSchema),
  // 所有已经注册的用户
  Register: mongoose.model('Register', RegisterSchema),
  // 所有的用户的信息
  Users: mongoose.model('Users', UsersSchema),
  // 某一用户的个人用户信息
  UsersInfo: mongoose.model('UsersInfo', UsersInfoSchema)
}

module.exports = Models
